package admin

import (
	"editor/constant"
	"editor/utils"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"strings"
	"time"
)

type UploadRespDataFiles struct {
	FormName  string `json:"formName"`
	FileName  string `json:"fileName"`
	FileExt   string `json:"fileExt"`
	FileIsImg bool   `json:"fileIsImg"`
	Url       string `json:"url"`
	Size      int64  `json:"size"`
}

type UploadRespData struct {
	Files []UploadRespDataFiles `json:"files"`
}

func ImagePasteUploadHandler(c *gin.Context) {
	var err error
	var respData UploadRespData
	form, _ := c.MultipartForm()
	for formName, f := range form.File {
		for _, file := range f {

			ext := path.Ext(file.Filename)
			if ext == "" {
				c.JSON(http.StatusOK, constant.Response{Msg: "获取文件扩展名出错", Code: 2})
			}
			ext = strings.ToLower(ext)
			name := time.Now().Format("file_20060102_150405_") + utils.GenerateRandomString(6) + ext
			dst := "./static/images/" + name

			err = c.SaveUploadedFile(file, dst)
			if err != nil {
				c.JSON(http.StatusOK, constant.Response{Msg: "保存文件出错,error:" + err.Error(), Code: 3})
				return
			}

			var url string
			ossUrl, err2 := PutObject(dst, name)
			if err2 != nil || ossUrl == "" {
				url = "/images/" + name
			} else {
				url = ossUrl
			}

			respData.Files = append(respData.Files, UploadRespDataFiles{
				FormName:  formName,
				FileName:  file.Filename,
				FileExt:   ext,
				FileIsImg: checkFileIsImgByExt(ext),
				Url:       url,
				Size:      file.Size,
			})
		}
	}

	c.JSON(http.StatusOK, constant.Response{Msg: "success", Code: 0, Data: respData})
}

func checkFileIsImgByExt(ext string) bool {
	if ext == "" {
		return false
	}

	return utils.StringInArray(ext, []string{".jpg", ".png", ".jpeg", ".gif", ".ico", ".tiff", ".tif"})
}

func PutObject(localFile string, ossObjectFileName string) (url string, err error) {

	//线上环境才允许使用oss
	if constant.Config.App.Env != "prd" {
		return "", nil
	}

	cnf := constant.Config.ALiYunOss
	client, err := oss.New(cnf.Endpoint, cnf.AccessKey, cnf.AccessSecret)
	if err != nil {
		return "", err
	}

	bucket, err := client.Bucket(cnf.BucketName)
	if err != nil {
		return "", err
	}

	err = bucket.PutObjectFromFile(ossObjectFileName, localFile)
	if err != nil {
		return "", err
	}

	if cnf.Domain == "" {
		err = fmt.Errorf("aliyun oss config for domian is empty")
	}

	return cnf.Domain + "/" + ossObjectFileName, nil
}
